package com.itheima.comfyui.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.comfyui.core.dto.request.UserLoginReqDTO;
import com.itheima.comfyui.core.dto.respone.UserLoginResDTO;
import com.itheima.comfyui.core.mapper.UserMapper;
import com.itheima.comfyui.core.pojo.User;
import com.itheima.comfyui.core.service.IUserService;
import com.itheima.comfyui.core.util.JWTUtils;
import org.apache.coyote.BadRequestException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl  extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public UserLoginResDTO login(UserLoginReqDTO userLoginReqDTO) throws BadRequestException {
        if(StringUtils.isEmpty(userLoginReqDTO.getUsername()) || StringUtils.isEmpty(userLoginReqDTO.getPassword())){
            throw new BadRequestException("用户名或密码不能为空");
        }

        User user = lambdaQuery()
                .or(StrUtil.isNotEmpty(userLoginReqDTO.getUsername()),(c)->{
                    c.eq(User::getMobile, userLoginReqDTO.getUsername());
                })
                .or(StrUtil.isNotEmpty(userLoginReqDTO.getUsername()),(c)->{
                    c.eq(User::getUsername, userLoginReqDTO.getUsername());
                })
                .one();
        //判断用户是否存在
        //验证密码
        if(user == null || !BCrypt.checkpw(userLoginReqDTO.getPassword(), user.getPassword())) {
            throw new BadRequestException("手机号或密码不匹配");
        }
        return generateLoginInfo(user);
    }

    private UserLoginResDTO generateLoginInfo(User user) {
        UserLoginResDTO userLoginResDTO = BeanUtil.toBean(user, UserLoginResDTO.class);
        if(StrUtil.isEmpty(userLoginResDTO.getName())){
            userLoginResDTO.setName(user.getUsername());
        }
        if(StrUtil.isEmpty(userLoginResDTO.getName())){
            userLoginResDTO.setName(user.getMobile());
        }
        // 生成token
        userLoginResDTO.setToken(JWTUtils.createJWT(userLoginResDTO.getId(),userLoginResDTO.getName()));
        return userLoginResDTO;
    }
}
